from datetime import datetime
import pytz
from kubernetes import client, config

# 指定配置文件路径
config.load_kube_config(config_file='config')

# 创建 Kubernetes API 客户端
v1 = client.CoreV1Api()

namespaces = ['my-test', 'opx']  # 命名空间名称列表

# 遍历每个命名空间下的 Pod 列表
for namespace in namespaces:
    pod_list = v1.list_namespaced_pod(namespace, watch=False)

    # 输出命名空间名称
    print(f'NAMESPACE: {namespace}')
    print(f'{"NAME":30} {"READY":10} {"STATUS":15} {"RESTARTS":>12} {"AGE":>5}')

    # 遍历 Pod 列表
    for pod in pod_list.items:
        # 获取所有容器状态信息
        container_statuses = pod.status.container_statuses
        if container_statuses is not None:
            ready_count = 0
            for status in container_statuses:
                if status.ready:
                    ready_count += 1

                if status.state.waiting is not None or status.state.terminated is not None:
                    pod_status = 'Error'
                    break
            else:
                pod_status = 'Running'

            restart_count = container_statuses[0].restart_count if container_statuses else 0
        else:
            ready_count = 0
            pod_status = 'Pending'
            restart_count = 0

        created_at = pod.metadata.creation_timestamp.timestamp()
        current_time = datetime.now(pytz.utc)
        age = round((current_time.timestamp() - created_at) / 3600, 1)

        # 打印输出每个 Pod 的名称、状态、重启次数和年龄
        print(f'{pod.metadata.name:30} {ready_count}/{len(container_statuses):<4} {pod_status:15} {restart_count:>12} {age:>3.1f}h')

    # 输出分隔符
    print('-' * 80)
